package com.example.creatation.prototype;

import java.util.HashMap;
import java.util.Map;

public class Mybatis {

    private final Map<String, User> userCache = new HashMap<>();

    /**
     * 从数据库查询数据
     *
     * @return User
     */
    public User getUser(String username) {
        User user = null;
        //缓存中没有
        if (!userCache.containsKey(username)) {
            //查询数据库
            user = getUserFromDB(username);
            user = user.clone();
        } else {
            // 从缓存中直接拿，脏缓存问题
            //原型已经拿到，但是不能直接给
            user = userCache.get(username);
        }
        //从这个对象中快速得到一个克隆体 == 原型模式
        user = user.clone();
        // 模拟数据库
        return user;
    }

    private User getUserFromDB(String username) {
        System.out.println("from DB select User :" + username);
        User user = new User();
        user.setAge(18);
        user.setUsername(username);
        userCache.put(username, user);
        return user;
    }
}
